#include "FindDevicesReply.hpp"
#include "../ExceptionUtil.hpp"
#include "../KieperException.hpp"
#include "../NetUtil.hpp"

#include <algorithm>

static const unsigned int DESC_SIZE = 40;
static const unsigned int DESC_PL_DELIM = DESC_SIZE + 1;
static const unsigned int PAYLOAD_SIZE = DESC_PL_DELIM + 2;

namespace kieper {
    // using std::ostream;
    using std::strlen;
    using std::copy;

    FindDevicesReply::FindDevicesReply(uint16_t deviceId, uint16_t port, 
        const char* description) : Message(
        new Packet(PAYLOAD_SIZE, Packet::TYPE_CONTROL, Packet::DELIVERY_ASYNC,
        Packet::SCOPE_GLOBAL, Packet::DIRECTION_RESPONSE, 0)) {
        
        unsigned int descLength;
        if ((descLength = strlen(description)) > DESC_SIZE) {
            THROW(KieperException, "The size of the description cannot be greater then 40");
        }
        
        getPacket().setDeviceId(deviceId);
        netutil::setAsNbo16(getPacket().getPayload(), 0, port);
        copy(description, description + descLength + 1, getPacket().getPayload() + 2);
    }

    FindDevicesReply::FindDevicesReply(const IncomingPacket& packet) : 
        Message(new Packet(PAYLOAD_SIZE, packet.getBuffer())) {}

    FindDevicesReply::~FindDevicesReply() {}

    uint16_t FindDevicesReply::getDeviceId() const {
        return getPacket().getDeviceId();
    }
    
    uint16_t FindDevicesReply::getPort() const {
        return netutil::getFromNbo16(getPacket().getPayload(), 0);
    }
    
    const char* FindDevicesReply::getDescription() const {
        return getPacket().getPayload() + 2;
    }
}
